#include"socket.hpp"
#include<poll.h>
uint16_t defaultport=8080;
const int count=128;
const int noevent=-1;
class pollserver
{
public:
pollserver(uint16_t port=defaultport)
:_port(port)
{
   for(int i=0;i<count;i++)
     {
      num[i].fd=-1;
      num[i].events=noevent;
      num[i].revents=noevent;

     }
    

}

void init()
{
 
_listensock.Socket();
_listensock.Bind(_port);
_listensock.Listen();

}
void start()
{  
  num[0].fd=_listensock.fd();
  num[0].events=POLLIN;
  for(   ;   ;)
  {
    int n=poll(num,count,-1);
    

    if(n==0)
    {
       cout<<"poll time out..."<<endl;
    }
    else if(n<0)
    {  cout<<"poll error..."<<endl;}
    else
    {cout<<"poll is ok"<<endl;
     deal();
    
    }
  
  }


}
void deal()
{
    for(int i=0;i<count;i++)
      {   int fd=num[i].fd;
         if(fd==-1)
         continue;
          
       

         if(num[i].revents&POLLIN)
         {
           if(fd==_listensock.fd())
           {
             accepter();

           }
           else
           {

             reader(fd,i);


           }



         }
 








      }



}
void accepter()
{   
    uint16_t clientport;
    string clientip;
     int sock=_listensock.Accept(&clientport,&clientip);

     if(sock<0)
     {
        cout<<"accept error..."<<endl;
       
     }
     
     cout<<"clientport:"<<clientport<<"clientip:"<<clientip<<endl;

     int pos=1;
     for( ; pos<count;pos++)
     {
        if(num[pos].fd==-1)
        {break;}



     }
     if(pos!=count)
     {
        num[pos].fd=sock;
        num[pos].events=POLLIN;

     }
     else
     {
       close(sock);
       cout<<"no position..."<<endl;

     }

}
void reader(int fd,int pos)
{
   char buffer[1024];
   int n=read(fd,buffer,sizeof(buffer));
   if(n>0)
   {
      buffer[n]=0;
      cout<<buffer<<endl;
  
   }
   else if(n==0)
   {
      num[pos].fd=-1;
      num[pos].events=noevent;
      num[pos].revents=noevent;
      close(fd);


   }
   else
   {
      num[pos].fd=-1;
      num[pos].events=noevent;
       num[pos].revents=noevent;
       close(fd);



   }





}

private:
sock  _listensock;
uint16_t _port;
struct pollfd num[count];

};